package com.zmn.oms.dubbo.impl.normal.order;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.oms.common.dio.normal.order.CheckOrderServiceDIO;
import com.zmn.oms.common.dio.normal.order.NormalOrderWorkAddDIO;
import com.zmn.oms.common.dio.normal.order.OrderWorkQuery;
import com.zmn.oms.dubbo.dto.zmn.order.NewOrderDRO;
import com.zmn.oms.dubbo.impl.zmn.order.OrderWorkBaseRemoteService;
import com.zmn.oms.dubbo.interfaces.normal.order.NormalOrderWorkRemoteService;
import com.zmn.oms.dubbo.utils.DubboConsts;
import com.zmn.oms.model.dto.order.NewOrderDistributeMasterDTO;
import com.zmn.oms.model.dto.order.NewOrderExternalShopDTO;
import com.zmn.oms.model.dto.order.zmn.CheckManageCompanyDTO;
import com.zmn.oms.model.dto.order.zmn.ZsNormalNewOrderDTO;
import com.zmn.oms.model.dto.product.OrderProductDTO;
import com.zmn.oms.model.entity.post.OrderPost;
import com.zmn.oms.model.entity.serviceitem.OrderServiceItem;
import com.zmn.oms.zmn.business.interfaces.work.OrderWorkAssignBService;
import com.zmn.oms.zmn.business.interfaces.work.ZsOrderWorkQueryBService;
import com.zmn.pay.common.constant.PayConsts;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 类描述：普通订单
 *
 * @author wangxiaokun
 * @since 2021/04/06 10:20
 */
@Slf4j
@Service(loadbalance = "roundrobin", timeout = 10000, retries = 0, version = DubboConsts.INTERFACE_VERSION, validation = "true")
public class NormalOrderWorkRemoteServiceImpl extends OrderWorkBaseRemoteService implements NormalOrderWorkRemoteService {

    private static final String TAG = "新普通单";

    @Autowired
    private OrderWorkAssignBService orderWorkAssignBService;
    @Autowired
    private ZsOrderWorkQueryBService zsOrderWorkQueryBService;

    @Override
    public ResponseDTO<Map<String, Object>> getDynamicOrderWorkInfo(OrderWorkQuery orderWorkQuery) {
        log.info("动态查询工单数据入参：[{}]", JSON.toJSONString(orderWorkQuery));

        try {
            Map<String, Object> map = zsOrderWorkQueryBService.findDynamicOrderWorkInfo(orderWorkQuery);
            log.info("[{}]动态查询工单数据结果：【{}】", orderWorkQuery.getOrderId(), JSON.toJSONString(map));
            return ResponseDTO.success(map);
        } catch (Exception e) {
            log.error("动态查询工单数据异常：[{}]", e.getMessage());
            e.printStackTrace();
            return ResponseDTO.fail();
        }
    }

    @Override
    public ResponseDTO<NewOrderDRO> addOrder(NormalOrderWorkAddDIO normalOrderWorkAddDIO) {

        log.info("[{}] 添加订单：{}", TAG, JSON.toJSONString(normalOrderWorkAddDIO));

        if (StringUtils.isBlank(normalOrderWorkAddDIO.getOperator())) {
            normalOrderWorkAddDIO.setOperator("系统");
        }

        //基础信息
        ZsNormalNewOrderDTO dto = BeanMapper.map(normalOrderWorkAddDIO, ZsNormalNewOrderDTO.class);
        dto.setIp(normalOrderWorkAddDIO.getOperatorIP());

        // 订单基础信息
        BeanMapper.copy(normalOrderWorkAddDIO.getOrderWorkBaseDIO(), dto);

        // 产品信息
        OrderProductDTO orderProductDTO = BeanMapper.map(normalOrderWorkAddDIO.getOrderProductDIO(), OrderProductDTO.class);
        dto.setOrderProductList(Lists.newArrayList(orderProductDTO));

        // 服务项
        List<OrderServiceItem> orderServiceItemList = BeanMapper.mapList(normalOrderWorkAddDIO.getOrderProductDIO().getOrderServiceItemList(), OrderServiceItem.class);
        dto.setOrderServiceItemList(orderServiceItemList);

        // 用户信息
        BeanMapper.copy(normalOrderWorkAddDIO.getUserDIO(), dto);
        dto.setUserName(StringUtils.defaultString(normalOrderWorkAddDIO.getUserDIO().getContactName(), normalOrderWorkAddDIO.getUserDIO().getUserName()));
        // 优惠信息
        if (Objects.nonNull(normalOrderWorkAddDIO.getOrderAmountAndDiscountDIO())) {
            BeanMapper.copy(normalOrderWorkAddDIO.getOrderAmountAndDiscountDIO(), dto);
            List<String> couponCodes = normalOrderWorkAddDIO.getOrderAmountAndDiscountDIO().getCouponCodes();
            if (CollectionUtil.isNotNullOrEmpty(couponCodes)){
                dto.setDiscountItemCodes(couponCodes);
            }
        }

        // 渠道预付款
        if (NumberUtil.isNotNullOrZero(dto.getChannelPrepayAmount())) {
            dto.setChannelPrepayStatus(PayConsts.PAY_STATUS_DONE);
        }

        // 扩展数据
        if (Objects.nonNull(normalOrderWorkAddDIO.getExtraData())){
            BeanMapper.copy(normalOrderWorkAddDIO.getExtraData(), dto);
            dto.setAutoDistribute(normalOrderWorkAddDIO.getExtraData().getDutyMasterId());
        }
        // 快递信息
        List<OrderPost> orderPostList = BeanMapper.mapList(normalOrderWorkAddDIO.getOrderPostList(), OrderPost.class);
        dto.setOrderPostList(orderPostList);
        // 派单工程师信息
        NewOrderDistributeMasterDTO distributeMasterDTO = BeanMapper.map(normalOrderWorkAddDIO.getDistributeMasterDIO(), NewOrderDistributeMasterDTO.class);
        dto.setDistributeMasterDTO(distributeMasterDTO);

        // 渠道扩展数据，目前只支持录入 外部渠道单号
        if (Objects.nonNull(normalOrderWorkAddDIO.getChannelApiExtraData())){
            dto.setOuterId(normalOrderWorkAddDIO.getChannelApiExtraData().getOuterId());
        }

        // 外部店铺
        if (Objects.nonNull(normalOrderWorkAddDIO.getExternalShopInfo())) {
            NewOrderExternalShopDTO externalShopDTO = new NewOrderExternalShopDTO();
            externalShopDTO.setExternalShopId(normalOrderWorkAddDIO.getExternalShopInfo().getExternalShopId());
            externalShopDTO.setInternalShopId(normalOrderWorkAddDIO.getExternalShopInfo().getInternalShopId());
            externalShopDTO.setInternalShopName(normalOrderWorkAddDIO.getExternalShopInfo().getInternalShopName());
            externalShopDTO.setInternalBranchShopName(normalOrderWorkAddDIO.getExternalShopInfo().getInternalBranchShopName());
            dto.setExternalShopInfo(externalShopDTO);
        }

        return super.addOrder(dto);
    }

    @Override
    public ResponseDTO checkOrderServiceCapacity(CheckOrderServiceDIO checkOrderServiceDIO) {

        log.info("[{}] 校验服务能力入参：{}", TAG, JSON.toJSONString(checkOrderServiceDIO));

        try {
            CheckManageCompanyDTO dto = BeanMapper.map(checkOrderServiceDIO, CheckManageCompanyDTO.class);
            boolean check = orderWorkAssignBService.checkServiceCapacity(dto);
            if (check) {
                return ResponseDTO.success();
            }

            return ResponseDTO.fail();
        } catch (Exception e) {
            log.error("校验订单服务能力异常：[{}]", e.getMessage());
            e.printStackTrace();
            return ResponseDTO.fail();
        }
    }

}
